package com.greenantmall.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.avos.avoscloud.AVUser;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.R;
import com.greenantmall.adapter.SelectAreaLeftAdapter;
import com.greenantmall.adapter.SelectAreaLeftAdapter.AreaBean;
import com.greenantmall.adapter.SelectAreaRightAdapter;
import com.greenantmall.adapter.SelectAreaRightAdapter.UpTownBean;
import com.greenantmall.bean.ServerSection;
import com.greenantmall.bean.StoreInfo;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.UtilTools;
import com.greenantmall.view.MSpinner;
import com.greenantmall.view.MSpinner.MSpinnerBean;
import com.greenantmall.view.MSpinner.OnMSpinnerItemClickListener;
import com.lsarah.utils.SystemBarTintManager;

public class SelectAreaActivity extends BaseActivity
{
	private Button mBtnBack;
	private MSpinner mCityMSpinner;
	private TextView mTvSearch;
	private TextView mTvTopDes;
	private ListView mAreaListView;
	private ListView mUpTownListView;
	private ProgressBar mProgressBar;
	private TextView mTvPrompt;
	
	private SelectAreaLeftAdapter mSelectAreaLeftAdapter;
	private SelectAreaRightAdapter mSelectAreaRightAdapter;
	private List<ServerSection> mServerSectionList;
	private List<MSpinnerBean> mCityMSpinnerBeanList;
	private List<AreaBean> mAreaBeanList;
	private List<UpTownBean> mUpTownList;
	private List<UpTownBean> mUpTownDataList;
	
	private String mCurSelectCity;
	private String mCurSelectArea;
	private String mCurSelectUpTown;
	
	private OnClickListener mOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if(v.equals(mBtnBack)) {
				SelectAreaActivity.this.finish();
			}
			else if(v.equals(mTvSearch)) {
				if(TextUtils.isEmpty(mCurSelectCity)) {
					return;
				}
				
				Intent intent = new Intent(SelectAreaActivity.this, SelectAreaSearchActivity.class);
				intent.putExtra(SelectAreaSearchActivity.KEY_SELECTED_SECTION, 
						(mCurSelectCity==null ? "" : mCurSelectCity));
				startActivity(intent);
			}
		}
	};
	
	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if(arg0.equals(mAreaListView)) {
				for(AreaBean ab : mAreaBeanList) {
					ab.isSelected = false;
				}
				AreaBean areaBean = mAreaBeanList.get(arg2);
				areaBean.isSelected = true;
				mSelectAreaLeftAdapter.notifyDataSetChanged();
				
				mCurSelectArea = areaBean.area;
				refreshUptown();
			}
			else if(arg0.equals(mUpTownListView)) {
				UpTownBean upTownBean = mUpTownDataList.get(arg2);
				mCurSelectUpTown = upTownBean.serverSection.getUptown();
				UtilTools.saveServerSection(getApplication(), upTownBean.serverSection);
				UtilTools.processUserChangeShoppingCart(SelectAreaActivity.this);
				
				Const.mStoreInfoCvs = null;
				if(AVUser.getCurrentUser() != null) {
					RetrieveDataAsyn.getInstance().getStoreInfosForStore(-1, new RetrieveDataListener() {
						@Override
						public void dataRetrieved(int requestId, Object data) {
							if(data != null) {
								Const.mStoreInfoCvs = (StoreInfo) data;
							}
							
							Intent intent = new Intent(SelectAreaActivity.this, PortalActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							SelectAreaActivity.this.startActivity(intent);
							AntHomeApplication.shoppingMap.clear();
							
							SelectAreaActivity.this.finish();
						}
					});
				} else {
					Intent intent = new Intent(SelectAreaActivity.this, PortalActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					SelectAreaActivity.this.startActivity(intent);
					AntHomeApplication.shoppingMap.clear();
					
					SelectAreaActivity.this.finish();
				}
			}
		}
	};
	
	private OnMSpinnerItemClickListener mOnMSpinnerItemClickListener = new OnMSpinnerItemClickListener() {
		@Override
		public void onMSpinnerItemClick(MSpinner mspinner, int position,
				MSpinnerBean bean) {
			mCurSelectCity = bean.contentStr;
			mCurSelectArea = "";
			mCurSelectUpTown = "";
			refreshArea();
			refreshUptown();
		}
	};
	
	private RetrieveDataListener mRetrieveDataListener = new RetrieveDataListener() {
		@Override
		public void dataRetrieved(int requestId, Object data) {
			if(data != null) {
				mServerSectionList = (List<ServerSection>)data;
				Const.mServerSectionList = mServerSectionList;
				Log.d("CEXX", "CEXX ---> SelectAreaActivity ---> mServerSectionList.size : " + mServerSectionList.size());
				if(mServerSectionList.size() != 0) {
					refreshCity();
			        // read saved uptown info
			        ServerSection uiServerSection = UtilTools.getServerSection(getApplication());
			        if(uiServerSection != null && !TextUtils.isEmpty(uiServerSection.getCity())) {
			        	mCurSelectCity = uiServerSection.getCity();
			        	mCurSelectArea = uiServerSection.getArea();
			        	mCurSelectUpTown = uiServerSection.getUptown();
			        }
			        else if(mCityMSpinnerBeanList.size() > 0){
			        	mCurSelectCity = mCityMSpinnerBeanList.get(0).contentStr;
			        }
			        refreshArea();
			        refreshUptown();
			        
			        mProgressBar.setVisibility(View.GONE);
			        mTvPrompt.setVisibility(View.GONE);
			        mAreaListView.setVisibility(View.VISIBLE);
			        mUpTownListView.setVisibility(View.VISIBLE);
				}
				else {
					mProgressBar.setVisibility(View.GONE);
			        mTvPrompt.setVisibility(View.VISIBLE);
			        mAreaListView.setVisibility(View.GONE);
			        mUpTownListView.setVisibility(View.GONE);
			        mTvPrompt.setText(getResources().getString(R.string.select_area_search_prompt_load_data_error));
				}
			}
			else {
				mProgressBar.setVisibility(View.GONE);
		        mTvPrompt.setVisibility(View.VISIBLE);
		        mAreaListView.setVisibility(View.GONE);
		        mUpTownListView.setVisibility(View.GONE);
		        mTvPrompt.setText(getResources().getString(R.string.select_area_search_prompt_load_data_error));
			}
		}
	};
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        SystemBarTintManager.setContentView(this, R.layout.select_area, getResources().getColor(R.color.green));
        mBtnBack = (Button)findViewById(R.id.select_area_top_arrow_left);
        mCityMSpinner = (MSpinner)findViewById(R.id.select_area_top_mspinner);
        mTvSearch = (TextView)findViewById(R.id.select_area_et_search);
        mTvTopDes = (TextView)findViewById(R.id.select_area_top_des);
        mAreaListView = (ListView)findViewById(R.id.select_area_listview_left);
        mUpTownListView = (ListView)findViewById(R.id.select_area_listview_right);
        mProgressBar = (ProgressBar)findViewById(R.id.select_area_prgressbar);
    	mTvPrompt = (TextView)findViewById(R.id.select_area_tv_prompt);
        
    	mTvSearch.setOnClickListener(mOnClickListener);
        mBtnBack.setOnClickListener(mOnClickListener);
        mCityMSpinner.setTitleTextColor(getResources().getColor(android.R.color.white));
        mCityMSpinner.setTitleGravity(Gravity.CENTER);
        mCityMSpinner.setHint(getResources().getString(R.string.choose_city));
        mCityMSpinner.setOnMSpinnerItemClickListener(mOnMSpinnerItemClickListener);
        mCityMSpinner.setDisplayItemInTitle(false);
        mAreaListView.setOnItemClickListener(mOnItemClickListener);
        mUpTownListView.setOnItemClickListener(mOnItemClickListener);
        
        mCityMSpinnerBeanList = new ArrayList<MSpinnerBean>();
        mAreaBeanList = new ArrayList<AreaBean>();
        mUpTownList = new ArrayList<UpTownBean>();
        mUpTownDataList = new ArrayList<UpTownBean>();
        
        RetrieveDataAsyn.getInstance().getServerSection(-1, mRetrieveDataListener);
        mProgressBar.setVisibility(View.VISIBLE);
        mTvPrompt.setVisibility(View.GONE);
        mAreaListView.setVisibility(View.GONE);
        mUpTownListView.setVisibility(View.GONE);
    }
    
    private void refreshCity() {
    	for(ServerSection section : mServerSectionList) {
        	boolean have = false;
        	for(MSpinnerBean bean : mCityMSpinnerBeanList) {
        		if(bean.contentStr.equals(section.getCity())) {
        			have = true;
        			break;
        		}
        	}
        	
        	if(!have) {
        		MSpinnerBean bean = new MSpinnerBean();
        		bean.contentStr = section.getCity();
        		mCityMSpinnerBeanList.add(bean);
        	}
        }
        mCityMSpinner.setDropDownListData(mCityMSpinnerBeanList);
    }
    
    private void refreshArea() {
    	List<String> areaList = new ArrayList<String>();
		for(ServerSection section : mServerSectionList) {
			if(section.getCity().equals(mCurSelectCity) && !areaList.contains(section.getArea())) {
				areaList.add(section.getArea());
			}
		}
		mTvTopDes.setText(mCurSelectCity);
		
		mAreaBeanList.clear();
		for(String area : areaList) {
			AreaBean areaBean = new AreaBean();
			areaBean.area = area;
			
			int count = 0;
			for(ServerSection section : mServerSectionList) {
				if(section.getArea().equals(area) && section.getCity().equals(mCurSelectCity)) {
					count++;
				}
			}
			areaBean.uptownCount = count;
			
			mAreaBeanList.add(areaBean);
		}
		
		if(TextUtils.isEmpty(mCurSelectArea)) {
			if(mAreaBeanList.size() > 0) {
				mAreaBeanList.get(0).isSelected = true;
				mCurSelectArea = mAreaBeanList.get(0).area;
			}
		}
		else {
			for(AreaBean bean : mAreaBeanList) {
				if(mCurSelectArea.equals(bean.area)) {
					bean.isSelected = true;
					break;
				}
			}
		}
		
		if(mSelectAreaLeftAdapter == null) {
			mSelectAreaLeftAdapter = new SelectAreaLeftAdapter(SelectAreaActivity.this, mAreaBeanList);
			mAreaListView.setAdapter(mSelectAreaLeftAdapter);
		}
		else {
			mSelectAreaLeftAdapter.notifyDataSetInvalidated();
		}
    }
    
    private void refreshUptown() {
    	mUpTownList.clear();
		for(ServerSection section : mServerSectionList) {
			if(section.getArea().equals(mCurSelectArea) && section.getCity().equals(mCurSelectCity)) {
				UpTownBean upTownBean = new UpTownBean();
				upTownBean.serverSection = section;
				mUpTownList.add(upTownBean);
			}
		}
		
		mUpTownDataList.clear();
		mUpTownDataList.addAll(mUpTownList);
		if(mSelectAreaRightAdapter == null) {
			mSelectAreaRightAdapter = new SelectAreaRightAdapter(SelectAreaActivity.this, mUpTownDataList);
			mUpTownListView.setAdapter(mSelectAreaRightAdapter);
		}
		else {
			mSelectAreaRightAdapter.notifyDataSetInvalidated();
		}
    }
}
